/// 模板变量模型 - Template Variable Model
/// 表示 Prompt 中的可替换变量
class TemplateVariable {
  /// 变量名称 - Variable name
  final String name;

  /// 变量描述 - Variable description
  final String description;

  /// 默认值 - Default value
  final String defaultValue;

  /// 是否必需 - Whether required
  final bool isRequired;

  /// 变量类型 - Variable type (text, number, boolean, select, multiline)
  final String type;

  TemplateVariable({
    required this.name,
    required this.description,
    this.defaultValue = '',
    this.isRequired = false,
    this.type = 'text',
  });

  /// 从 JSON 创建模板变量 - Create TemplateVariable from JSON
  TemplateVariable.fromJson(Map<String, dynamic> json)
      : name = json['name'] ?? '',
        description = json['description'] ?? '',
        defaultValue = json['defaultValue'] ?? '',
        isRequired = json['isRequired'] ?? false,
        type = json['type'] ?? 'text';

  /// 转换为 JSON - Convert to JSON
  Map<String, dynamic> toJson() {
    return {
      'name': name,
      'description': description,
      'defaultValue': defaultValue,
      'isRequired': isRequired,
      'type': type,
    };
  }
}

/// Prompt 模型 - Prompt Model
/// 表示一个完整的 Prompt 对象，包含所有相关信息
class PromptModel {
  /// Prompt ID
  final String id;

  /// 标题 - Title
  final String title;

  /// 描述 - Description
  final String description;

  /// 内容 - Content
  final String content;

  /// 分类 - Category
  final String category;

  /// 标签列表 - Tags list
  final List<String> tags;

  /// 创建时间 - Created time
  final DateTime createdAt;

  /// 最后修改时间 - Last modified time
  final DateTime lastModified;

  /// 版本号 - Version number
  final int version;

  /// 文件路径 - File path
  final String filePath;

  /// 文件格式 - File format
  final String fileFormat;

  /// 元数据 - Metadata
  final Map<String, dynamic> metadata;

  /// 使用次数 - Usage count
  final int usageCount;

  /// 模板变量列表 - Template variables list
  final List<TemplateVariable> templateVariables;

  PromptModel({
    required this.id,
    required this.title,
    required this.content,
    required this.tags,
    required this.category,
    required this.description,
    required this.createdAt,
    required this.lastModified,
    required this.version,
    required this.filePath,
    required this.fileFormat,
    required this.metadata,
    this.usageCount = 0,
    this.templateVariables = const [],
  });

  /// 从 JSON 创建 Prompt 模型 - Create PromptModel from JSON
  PromptModel.fromJson(Map<String, dynamic> json)
      : id = json['id'] ?? '',
        title = json['title'] ?? '',
        description = json['description'] ?? '',
        content = json['content'] ?? '',
        category = json['category'] ?? '',
        tags = List<String>.from(json['tags'] ?? []),
        createdAt = DateTime.parse(
            json['createdAt'] ?? DateTime.now().toIso8601String()),
        lastModified = DateTime.parse(
            json['lastModified'] ?? DateTime.now().toIso8601String()),
        version = json['version'] ?? 1,
        filePath = json['filePath'] ?? '',
        fileFormat = json['fileFormat'] ?? 'md',
        metadata = Map<String, dynamic>.from(json['metadata'] ?? {}),
        usageCount = json['usageCount'] ?? 0,
        templateVariables = (json['templateVariables'] as List<dynamic>? ?? [])
            .map((v) => TemplateVariable.fromJson(v as Map<String, dynamic>))
            .toList();

  /// 转换为 JSON - Convert to JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'description': description,
      'content': content,
      'category': category,
      'tags': tags,
      'createdAt': createdAt.toIso8601String(),
      'lastModified': lastModified.toIso8601String(),
      'version': version,
      'filePath': filePath,
      'fileFormat': fileFormat,
      'metadata': metadata,
      'usageCount': usageCount,
      'templateVariables': templateVariables.map((v) => v.toJson()).toList(),
    };
  }
}

/// PromptModel 扩展方法 - PromptModel Extension Methods
/// 提供业务逻辑方法，保持 Model 类的纯净性
extension PromptModelExtensions on PromptModel {
  /// 是否收藏 - Whether favorite
  bool getIsFavorite() => metadata['isFavorite'] ?? false;

  /// 格式 - Format
  String getFormat() => fileFormat;

  /// 更新时间 - Updated time (兼容性)
  DateTime getUpdatedAt() => lastModified;

  /// 是否有模板变量 - Whether has template variables
  bool getHasTemplateVariables() => templateVariables.isNotEmpty;

  /// 内容预览 - Content preview
  String getContentPreview() {
    if (content.isEmpty) return '';
    
    // 移除多余的空白字符并截取前150个字符
    final cleanContent = content.replaceAll(RegExp(r'\s+'), ' ').trim();
    if (cleanContent.length <= 150) {
      return cleanContent;
    }
    
    return '${cleanContent.substring(0, 150)}...';
  }

  /// 增加使用次数 - Increment usage count
  PromptModel incrementUsage() {
    return PromptModel(
      id: id,
      title: title,
      content: content,
      tags: tags,
      category: category,
      description: description,
      createdAt: createdAt,
      lastModified: DateTime.now(),
      version: version,
      filePath: filePath,
      fileFormat: fileFormat,
      metadata: metadata,
      usageCount: usageCount + 1,
      templateVariables: templateVariables,
    );
  }

  /// 切换收藏状态 - Toggle favorite status
  PromptModel toggleFavorite() {
    final newMetadata = Map<String, dynamic>.from(metadata);
    newMetadata['isFavorite'] = !getIsFavorite();

    return PromptModel(
      id: id,
      title: title,
      content: content,
      tags: tags,
      category: category,
      description: description,
      createdAt: createdAt,
      lastModified: DateTime.now(),
      version: version,
      filePath: filePath,
      fileFormat: fileFormat,
      metadata: newMetadata,
      usageCount: usageCount,
      templateVariables: templateVariables,
    );
  }

  /// 获取缺失的必需变量 - Get missing required variables
  List<String> getMissingRequiredVariables(Map<String, String> values) {
    final missing = <String>[];
    for (final variable in templateVariables) {
      if (variable.isRequired) {
        final value = values[variable.name];
        if (value == null || value.trim().isEmpty) {
          missing.add(variable.name);
        }
      }
    }
    return missing;
  }

  /// 替换变量 - Replace variables
  String replaceVariables(Map<String, String> values) {
    String result = content;
    for (final variable in templateVariables) {
      final value = values[variable.name] ?? variable.defaultValue;
      result = result.replaceAll('{{${variable.name}}}', value);
    }
    return result;
  }

  /// 内容长度 - Content length
  int getContentLength() => content.length;

  /// 单词数 - Word count
  int getWordCount() => content.split(RegExp(r'\s+')).length;

  /// 行数 - Line count
  int getLineCount() => content.split('\n').length;

  /// 获取统计信息 - Get statistics
  Map<String, dynamic> getStatistics() {
    return {
      '字符数': getContentLength(),
      '单词数': getWordCount(),
      '行数': getLineCount(),
      '标签数': tags.length,
      '模板变量数': templateVariables.length,
      '使用次数': usageCount,
      '创建时间': createdAt.toString().split('.')[0],
      '最后修改': lastModified.toString().split('.')[0],
      '版本': version.toString(),
    };
  }

  /// 搜索匹配 - Search matching
  bool matchesSearch(String query) {
    if (query.isEmpty) return true;
    
    final lowerQuery = query.toLowerCase();
    return title.toLowerCase().contains(lowerQuery) ||
           description.toLowerCase().contains(lowerQuery) ||
           content.toLowerCase().contains(lowerQuery) ||
           category.toLowerCase().contains(lowerQuery) ||
           tags.any((tag) => tag.toLowerCase().contains(lowerQuery));
  }

  /// 包含标签 - Contains tags
  bool containsTags(List<String> searchTags) {
    if (searchTags.isEmpty) return true;
    
    return searchTags.every((searchTag) => 
        tags.any((tag) => tag.toLowerCase() == searchTag.toLowerCase()));
  }
}
